import { Component, OnInit, ViewChild } from "@angular/core";
import { FetchService } from "src/app/core/net/fetch.service";
import { NzMessageService, NzTreeComponent, NzTreeNode } from "ng-zorro-antd";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { map, takeUntil } from "rxjs/operators";
import { UtilService } from "src/app/core/util/util.service";
import { MenuItemModel } from "src/app/core/auth/auth.service";
import * as _ from "lodash";

@Component({
  selector: "app-role-manage",
  templateUrl: "./role-manage.component.html",
  styleUrls: [
    "../user-manage/user-manage.component.scss",
    "./role-manage.component.scss"
  ]
})
export class RoleManageComponent implements OnInit {
  @ViewChild("nzTreeComponent")
  nzTreeComponent: NzTreeComponent;
  @ViewChild("nzMngTreeComponent") nzMngTreeComponent: NzTreeComponent;
  tableData: Array<any> = [];
  pageNum = 1;
  pageSize = 10;
  total: number;
  modalTitle: string = "";
  modalShow: boolean = false;
  nzBodyStyle: any = {
    padding: "16px 20px 0"
  };

  form: FormGroup;
  // dictHash = {};
  roleTypes: any[] = [];
  useableList: any[] = [];
  roleMapper: any = {};
  useableMapper: any = {};

  menuTree;
  menuList = [];
  defaultKeys = [];
  checkedKeys = [];

  mngTree;
  mngList = [];
  checkedMngKeys = [];
  defaultKeysActive = [];
  constructor(
    private fetchService: FetchService,
    private message: NzMessageService,
    private fb: FormBuilder,
    private utilService: UtilService
  ) {}

  ngOnInit() {
    this.queryInfo();
    this.getDictValue("00002").subscribe(res => {
      this.roleTypes = res.list;
      this.roleMapper = res.mapper;
    });
    this.getDictValue("00001").subscribe(res => {
      this.useableList = res.list;
      this.useableMapper = res.mapper;
    });
    this.getMenuTree();
    this.getMngTree();

    this.form = this.fb.group({
      id: [""],
      name: ["", Validators.required],
      roleType: ["", Validators.required],
      remarks: [""],
      useable: [""]
      // delFlag: [""],
      // createBy: [""],
      // createDate: [""],
      // updateBy: [""],
      // updateDate: [""]
    });
  }

  reset(): void {
    this.queryInfo();
  }

  queryInfo(): void {
    this.fetchService
      .post<any>("sys/sysRole/list", {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      .subscribe(res => {
        this.total = res.total;
        this.tableData = res.list;
      });
  }

  getDictValue(typeId) {
    return this.fetchService
      .post<any>("sys/sysDictValue/list", {
        // 00001;是否可用; 00002;角色类型;
        dictTypeId: typeId
      })
      .pipe(
        map(res => {
          const list = res["list"] || [];
          const mapper = list.reduce((def, item) => {
            def[item.value] = item.label;
            return def;
          }, {});
          return {
            list,
            mapper
          };
        })
      );
  }

  getMenuTree() {
    this.fetchService
      .post<any>("sys/sysMenu/list", { pageSize: 1000 })
      .subscribe(res => {
        const menuList = res.list;
        menuList.sort((a, b) => {
          return a.sort - b.sort;
        });
        menuList.unshift({ id: "0", name: "菜单", parentIds: "" });
        this.utilService
          .flat2Nested<MenuItemModel>(menuList, {
            pathProperty: "parentIds",
            rootId: "0"
          })
          .subscribe(data => {
            this.menuList = [data];
          });
      });
  }

  getMngTree() {
    this.fetchService
        .post<any>("wrs/wrsBmanage/list", { })
        .subscribe(res => {

          const mngList = res.list;
          mngList.filter((item, index) => {

            item.id = item.id + "";
          });
          this.utilService
              .flat2Nested<any>(mngList, {
                pathProperty: "pid",
                parentIdProperty: 'pid',
                rootId: "1"
              })
              .subscribe(data => {

                this.mngList = [data];

              });
        });
  }
  initTree() {
    const menuTree = _.cloneDeep(this.menuList);
    this.getTreeData(menuTree);
    this.menuTree = menuTree;
  }

  initMngTree() {
    const mngTree = _.cloneDeep(this.mngList);
    this.getMngTreeData(mngTree);
    this.mngTree = mngTree;
  }
  getMngTreeData(data) {
    data.map(item => {
      item.title = item.manageName;
      item.key = item.id;
      if (item.id == "1") {
        item.expanded = true;
      }
      if (item.children && item.children.length) {
        item.expanded = true;
        this.getMngTreeData(item.children);
      } else {
        item.isLeaf = true;
        item.checked = this.checkedMngKeys.indexOf(item.id) > -1;
      }
    });
  }
  getTreeData(data) {
    data.map(item => {
      item.title = item.name;
      item.key = item.id;
      if (item.id == "0") {
        item.expanded = true;
      }
      if (item.children && item.children.length) {
        item.expanded = true;
        this.getTreeData(item.children);
      } else {
        item.isLeaf = true;
        item.checked = this.checkedKeys.indexOf(item.id) > -1;
      }
    });
  }

  menuCheck(data) {
    const checkedNodes = data.checkedKeys;
    this.checkedKeys = [];
    checkedNodes.map(node => {
      this.getChecked(node);
    });
  }

  mngListCheck(data) {
    const checkedNodes = data.checkedKeys;
    this.checkedMngKeys = [];
    checkedNodes.map(node => {
      this.getMngChecked(node);
    });
  }

  getChecked(node) {
    if (node.level == 2 && this.checkedKeys.indexOf(node.parentNode.key) < 0) {
      this.checkedKeys.push(node.parentNode.key);
    }

    if (node.level > 0) {
      this.checkedKeys.push(node.key);
    }

    if (node.children.length) {
      node.children.map(child => {
        this.getChecked(child);
      });
    }
  }
  getMngChecked(node) {
    if (node.level == 2 && this.checkedMngKeys.indexOf(node.key) < 0) {
      this.checkedMngKeys.push(node.key);
    }

    // if (node.level === 2) {
    //   this.checkedMngKeys.push(node.key);
    // }

    if (node.children.length) {
      node.children.map(child => {
        this.getMngChecked(child);
      });
    }
  }
  openEditModal(item?): void {
    if (item && item.id) {
      this.fetchService.get(`sys/sysRole/${item.id}`).subscribe(res => {
        this.modalTitle = "编辑角色";
        this.form.reset(item);
        this.checkedKeys = res["mids"] ? res["mids"].split(",") : [];
        this.checkedMngKeys = res["vids"] ? res["vids"].split(",") : [];
        this.defaultKeysActive = res["vids"] ? res["vids"].split(",") : [];

        this.initTree();
        this.initMngTree();
        this.modalShow = true;
      });
    } else {
      this.modalTitle = "新增角色";
      this.form.reset({});
      this.checkedKeys = [];
      this.checkedMngKeys = [];
      this.initTree();
      this.initMngTree();
      this.modalShow = true;
    }
  }

  onDelete(id) {
    this.fetchService.post("sys/sysRole/del", { id }).subscribe(resp => {
      this.message.info("删除成功");
      this.queryInfo();
    });
  }

  onConfirm() {
    if (!this.form.valid) {
      this.message.warning("信息填写有误");
      return;
    }
    if (!this.checkedKeys.length) {
      this.message.warning("请选择菜单");
      return;
    }
    const data = { ...this.form.value, mids: this.checkedKeys.join(","), vids: this.checkedMngKeys.join(',') };
    if (data.id) {
      this.fetchService.post("sys/sysRole/edit", data).subscribe(res => {
        this.modalShow = false;
        this.queryInfo();
      });
    } else {
      this.fetchService.post("sys/sysRole/add", data).subscribe(res => {
        this.modalShow = false;
        this.queryInfo();
      });
    }
  }
  onCancel() {
    this.modalShow = false;
  }
}
